// pages/caseReward/myRewardDet/myRewardDet.js
import request from '../../../utils/config.js';
import formatUtil from '../../../utils/util.js';
import cityData from '../../../utils/vendor/cityList.js';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showImageList:[],
    showPicTap:true,
    // userExt: {},
    memUserInfo: {},
    applyId: "",
    entrustDet: {},
    showPerInfo: false,//个人信息显示
    btnMsg: "提交",
    bankInfo: {}, 
    consultResult:"", //尽调结果
    entrustCaseDet:{}
  },

  //下拉执行
  onPullDownRefresh: function () {
    this.queryEntrustDet();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      applyId: options.applyId,
      entrustCaseDet:app.globalData.entrustCaseDet
    });
   
  },

  //尽调结果触发
  change_consultResult: function (e) {
    this.setData({
      consultResult: e.detail.value
    })
  },


  //跟人信息页面
  goPersonalInfo: function () {
    wx.navigateTo({
      url: '../bankInfo/bankInfo',
    })
  },

  //查询委托尽调详情
  queryEntrustDet: function () {
    let headerInfo = {
      sessionId: app.globalData.sessionId,
    }
    let bodyInfo = {
      applyId: this.data.applyId * 1 || ""
    }
    let _this = this;
    wx.showLoading({ title: '加载中', mask: true });
    request.requestLogin_api("queryEntrustConsultApply", headerInfo, bodyInfo, (obj) => {
      wx.stopPullDownRefresh();
      console.log("详情=", obj)
      wx.hideLoading(obj);
      if (obj.data.errorCode == '00') {
        let entrustDet = JSON.parse(obj.data.body);
        // entrustDet.entrustName = formatUtil.getEntrustNameById(entrustDet.entrustType + '');
        // entrustDet.operName = entrustDet.operName.substring(0, 1) + "律师";
        // entrustDet.endDate = formatUtil.checkYearMonthDay(entrustDet.endDate);
       
        //存储银行信息
        app.globalData.bankInfo.userName = entrustDet.userName;
        app.globalData.bankInfo.mobileNo = entrustDet.mobileNo;
        app.globalData.bankInfo.email = entrustDet.email;

        let accountNo = "";
        if (entrustDet.accountNo){
          app.globalData.bankInfo.accountName = entrustDet.accountName;
          app.globalData.bankInfo.accountNo = entrustDet.accountNo;
          app.globalData.bankInfo.openBankName = entrustDet.openBankName;
          app.globalData.bankInfo.accountType = entrustDet.accountType;
        }
        // console.log("app.globalData.bankInfo=", app.globalData.bankInfo)
        if (app.globalData.bankInfo.accountNo){
          let tempNo = app.globalData.bankInfo.accountNo;
          try{
            accountNo = tempNo.substring(0, 4) + " " + tempNo.substring(4, 8) + " " + tempNo.substring(8, 12) + " " + tempNo.substring(12, 16) + " " + tempNo.substring(16, tempNo.length);
          }catch(e){
            accountNo = tempNo;
          }
        }

        //如果状态为3：已提交，那么只能查看
        
        
        if (entrustDet.ecStatus == 3){
          let showImageList = [], consultResult = "";
          showImageList = entrustDet.resultAttach.split(',');
          consultResult = entrustDet.consultResult;
          _this.setData({
            showImageList: showImageList,
            consultResult: consultResult
          });
        }


        _this.setData({
          entrustDet: entrustDet,
          bankInfo: app.globalData.bankInfo,
          accountNo: accountNo
        });

      } else {
        wx.showModal({
          title: "查询失败",
          content: obj.data.errorMsg,
          confirmText: '确定',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
            } else if (res.cancel) {
            }
          }
        })
      }

    }, (obj) => {
      wx.stopPullDownRefresh();
      wx.hideLoading();
      wx.showModal({
        title: "加载失败",
        content: '请尝试下拉界面重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    })
  },

  //开始提交申请
  subApply: function(){
    console.log('111')
    if (this.data.entrustDet.status == '1'){
      wx.showModal({
        title: "悬赏待审批中",
        content: "待审批中请勿重复操作",
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
      return;
    }

    if (!this.data.showPerInfo) {
      this.setData({
        btnMsg: "确认信息",
        showPerInfo: true
      });
      return;
    }

    if (this.data.showImageList.length == 0) {
      wx.showToast({ title: '请上传尽调资料', icon: 'none' })
      return;
    }

    if (!this.data.consultResult){
      wx.showToast({ title: '请填写尽调结果备注信息', icon: 'none' })
      return;
    }

    //开始提交尽调结果
    let headerInfo = {
      sessionId: app.globalData.sessionId,
    }
    let bodyInfo = {
      entrustId: this.data.entrustDet.entrustId * 1,
      applyId: this.data.applyId,
      consultResult: this.data.consultResult,
      resultAttach: this.data.showImageList.join(','),
      email: this.data.bankInfo.email,
      mobileNo: this.data.bankInfo.mobileNo,
      userName: this.data.bankInfo.userName,
      accountType: this.data.bankInfo.accountType,
      accountName: this.data.bankInfo.accountName,
      accountNo: this.data.bankInfo.accountNo,
      openBankName: this.data.bankInfo.openBankName
    }
    console.log("bodyInfo=", bodyInfo)
    let _this = this;
    wx.showLoading({ title: '加载中', mask: true });
    request.requestLogin_api("submitEntrustConsultResult", headerInfo, bodyInfo, (obj) => {
      wx.stopPullDownRefresh();
      console.log("提交发布结果=", obj)
      wx.hideLoading(obj);
      if (obj.data.errorCode == '00') {
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 1500
        })
        setTimeout(function () {
          wx.navigateBack();
        }, 2000);
      } else {
        wx.showModal({
          title: "提交失败",
          content: obj.data.errorMsg,
          confirmText: '确定',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
            } else if (res.cancel) {
            }
          }
        })
      }

    }, (obj) => {
      wx.stopPullDownRefresh();
      wx.hideLoading();
      wx.showModal({
        title: "加载失败",
        content: '请尝试下拉界面重新加载',
        confirmText: '确定',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    })

  },


  //选择文件
  chooseImage: function () {
    var len = 9 - (this.data.showImageList).length;
    var _this = this;
    wx.chooseImage({
      count: len, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.log("选择照片=", res);
        var tempArray = _this.data.showImageList;
        tempArray = tempArray.concat(tempFilePaths);
        // console.log("照片几张=", tempArray.length);
        if (tempArray.length == 9) {
          _this.setData({
            showPicTap: false
          });
        }
        //开始上传图片
        _this.startUploadImage(tempFilePaths, _this, 0);
      }
    })
  },
 

  //开始上传图片
  startUploadImage: (flieList, _that, index) => {
    wx.showLoading({
      title: '正在上传...',
    });
    console.log("index=", index);
    console.log("flieList=", flieList.length);
    if (index > flieList.length - 1) {
      wx.hideLoading();
      wx.showToast({
        title: '上传成功',
        icon: 'success',
        duration: 1500
      })
      return;
    } else {
      let path = flieList[index];
      let _this = _that;
      let bodyInfo = {
        path: path
      }
      console.log("图片上传bodyInfo=", bodyInfo)
      request.requestUploadImg('pictures', bodyInfo, (res) => {
        console.log("上传图片成功=", res);
        var tempRealImgList = _this.data.showImageList;
        tempRealImgList.push(res.data);
        _this.setData({
          showImageList: tempRealImgList
        });
        let tempflag = index + 1;
        console.log("tempflag=" + tempflag)
        _this.startUploadImage(flieList, _this, tempflag);
      }, (res) => {
        console.log("上传图片失败=", res);
      })
    }
  },

  //删 除 oss 照 片
  delImage: function (e) {
    let tempArray = this.data.showImageList;
    let _this = this;
    if (tempArray.length > 0) {
      let index = e.currentTarget.dataset.key;
      let path = tempArray[index];
    
      if (typeof path != "undefined") {
        path = path.substr(43);
      } else {
        // console.log('上传文件出错', tempArray)
        // console.log('上传文件出错', index)
      }
      let bodyInfo = {
        fileName: path
      }

      request.post_api('delFiles/' + path, bodyInfo, (res) => {
        tempArray.splice(e.currentTarget.dataset.key, 1);
        _this.setData({
          showImageList: tempArray,
          showPicTap: true
        });
      }, (res) => {
        console.log("上传图片失败=", res);
      })
    } else {
      tempArray = new Array();
    }
  },

  //预览照片
  showImage: function (e) {
    console.log("点击预览照片", e.target.dataset.url);
    var tempUrl = e.target.dataset.url;
    wx.previewImage({
      current: tempUrl, // 当前显示图片的http链接
      urls: [tempUrl] // 需要预览的图片http链接列表
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      // userExt: app.globalData.userExt,
      memUserInfo: app.globalData.persionalInfo
    });
    
    this.queryEntrustDet();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})